#app/services/wechat_service.py
import hashlib
import time
import xmltodict
from flask import current_app
from app.models.salary import SalaryInfo
from flask_restful import Resource
from flask import request, current_app
from app.services.salary_service import SalaryService
from collections import OrderedDict
import xml.etree.ElementTree as ET
import time
import hashlib
class WechatService:
    @staticmethod
    def verify_signature(args):
        signature = args.get('signature', '')
        timestamp = args.get('timestamp', '')
        nonce = args.get('nonce', '')
        echostr = args.get('echostr', '')

        token = current_app.config['WECHAT_TOKEN']
        temp_list = [token, timestamp, nonce]
        temp_list.sort()
        temp_str = ''.join(temp_list)
        hash_obj = hashlib.sha1(temp_str.encode('utf-8'))

        if hash_obj.hexdigest() == signature:
            return echostr
        return 'Invalid signature'

    @staticmethod
    def handle_message(xml_data):
        xml_dict = xmltodict.parse(xml_data)
        msg_type = xml_dict['xml']['MsgType']
        from_user = xml_dict['xml']['FromUserName']
        to_user = xml_dict['xml']['ToUserName']

        if msg_type == 'text':
            content = xml_dict['xml']['Content'].strip()
            return WechatService.handle_text_message(content, from_user, to_user)

        return WechatService.create_reply(to_user, from_user, '暂不支持的消息类型')

    @staticmethod
    def handle_text_message(content, from_user, to_user):
        if '薪资' in content:
            company = content.replace('薪资', '').strip()
            salaries = SalaryInfo.query.filter_by(company=company).limit(5).all()

            if salaries:
                reply = f"{company}的薪资信息:\n\n"
                for salary in salaries:
                    reply += f"职位: {salary.position}\n"
                    reply += f"基本工资: {salary.base_salary}k\n"
                    reply += f"城市: {salary.city}\n"
                    reply += "-------------------\n"
            else:
                reply = f"暂无{company}的薪资信息"

        elif content == '菜单':
            reply = """
            【薪资查询】
            发送: 公司名+薪资
            例如: 字节跳动薪资
            
            【分享薪资】
            发送: 分享
            按提示填写信息
            
            【使用帮助】
            发送: 帮助
            获取详细指南
            """
        else:
            reply = '请发送正确的指令，发送"菜单"查看支持的功能'

        return WechatService.create_reply(to_user, from_user, reply)

    @staticmethod
    def create_reply(to_user, from_user, content):
        reply = {
            'xml': {
                'ToUserName': from_user,
                'FromUserName': to_user,
                'CreateTime': int(time.time()),
                'MsgType': 'text',
                'Content': content
            }
        }
        return xmltodict.unparse(reply)